import { Application } from "../Application";
import { ClientSocket } from "../server/FrontendServer";
import { miscCfg, sessCoder } from "../util/defines";
import { Session } from "./Session";

/**
 * 前端服务器会话
 */
export class FrontendSession extends Session {

    /** 会话字节流 */
    buf: Uint8Array;
    /** 客户端连接 */
    socket: ClientSocket;

    constructor(app: Application, socket: ClientSocket) {
        super(app, app.svr.id);
        this.socket = socket;
    }

    /**
     * 更新会话字节流
     */
    updateBuf() {
        this.buf = sessCoder.encode({
            uid: this.uid,
            sid: this.sid,
            setting: this.setting
        }).end();
    }

    /**
     * 绑定客户端id 绑定之后该会话才可与后端服务器进行通信
     * @param uid 
     */
    bind(uid: number) {
        if (this.uid != undefined || this.app.clients[uid]) return false;
        this.app.clients[uid] = this;
        this.uid = uid;
        this.updateBuf();
    }

    set(setting: { [key: string | number]: any }) {
        super.set(setting);
        this.updateBuf();
    }

    delete(...keys: (string | number)[]) {
        super.delete(...keys);
        this.updateBuf();
    }

    /**
     * 踢出服务器
     */
    kick() {
        delete this.app.clients[this.uid];
        this.uid = null;
        this.socket.close();
    }

    send(msgId: number, msg?: any) {
        this.socket.send(miscCfg.msgCoder.encode(msgId, msg));
    }

    sends(msgs: { msgId: number; msg?: any; }[]) {
        for (let msg of msgs) {
            this.send(msg.msg, msg.msgId);
        }
    }

}